package com.health.adapter;

import java.util.HashMap;
import java.util.List;

import com.health.model.LabelsBean;
import com.health.model.PeopleType;
import com.health.tools.DeleteDAData;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.SPUtil;
import com.health.viewscontrols.MainActivity_Menu_Tj;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.db.FDbManager;
import com.health.fragment.jtys.JTYSDA;
import com.health.viewscontrols.focusgroup.ChildActivity;
import com.health.viewscontrols.focusgroup.FJHActivity;
import com.health.viewscontrols.focusgroup.GXBActivity;
import com.health.viewscontrols.focusgroup.GXYActivity;
import com.health.viewscontrols.focusgroup.JSJBctivity;
import com.health.viewscontrols.focusgroup.MaternityActivity;
import com.health.viewscontrols.focusgroup.NCZActivity;
import com.health.viewscontrols.focusgroup.OlderActivity;
import com.health.viewscontrols.focusgroup.TNBActivity;
import com.health.viewscontrols.medical.BleMainActivity;
import com.health.viewscontrols.qyinfo.MemberDataActivity;
import com.health.viewscontrols.qyinfo.QYInfo;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tools.GlobalConts;
import com.health.tools.PopData;
import com.health.widget.CommomDialog;
import com.health.widget.LabelsView;
import com.health.widget.WaterMarkBg;
import com.novabluetooth.views.SBCLActivity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import static android.app.Activity.RESULT_OK;

/**
 * 家庭医生档案listAdapter
 * 
 * @author nova
 *
 */
public class JTYSDAAdapter extends BaseAdapter {

	private List<ARCHIVE_BASEINFO> infoList;
	private Context context;
	private String type;
	private HashMap<Integer, View> viewMap = new HashMap<>();
	private GridView gd_da;
	String strIntentId;

	public JTYSDAAdapter(Context context, List<ARCHIVE_BASEINFO> infoList, String type, GridView gd_da,String strIntentId) {
		super();
		this.context = context;
		this.infoList = infoList;
		this.type = type;
		this.gd_da = gd_da;
		this.strIntentId = strIntentId;
		for (int i=0;i<infoList.size();i++){
			Log.e("用户信息",infoList.get(i).toString());
		}
	}
	public void setInfoList(List<ARCHIVE_BASEINFO> infoList) {
		this.infoList = infoList;
	}


	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return infoList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return infoList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (!viewMap.containsKey(position) || viewMap.get(position) == null) {
			holder = new ViewHolder();
			convertView = View.inflate(context, R.layout.jtysda_item, null);

			holder.iv_tijian = (ImageView)convertView.findViewById(R.id.iv_tijian);
			holder.jtys_list_name = (TextView) convertView.findViewById(R.id.jtys_list_name);
			holder.jtys_list_age = (TextView) convertView.findViewById(R.id.jtys_list_age);
			holder.jtys_list_sex = (TextView) convertView.findViewById(R.id.jtys_list_sex);
			holder.jtys_list_phone = (TextView) convertView.findViewById(R.id.jtys_list_phone);
			holder.jtys_list_zdrq = (LabelsView) convertView.findViewById(R.id.jtys_list_zdrq);
			holder.jtys_list_address = (TextView) convertView.findViewById(R.id.jtys_list_address);
			holder.jtys_list_state_sign = (ImageView) convertView.findViewById(R.id.jtys_list_state_sign);
			holder.jtys_list_state_unsign = (ImageView) convertView.findViewById(R.id.jtys_list_state_unsign);
			holder.jtys_jiandang_time=convertView.findViewById(R.id.jtys_jiandang_time);
			holder.iv_sex = convertView.findViewById(R.id.iv_sex);
			holder.tv_phone = convertView.findViewById(R.id.tv_phone);
			holder.jtys_list_create = convertView.findViewById(R.id.jtys_list_create);
			holder.tv_cardid = convertView.findViewById(R.id.tv_cardid);

			holder.btn_tijian=convertView.findViewById(R.id.btn_tijian);
			holder.iv_signing=convertView.findViewById(R.id.iv_signing);
			holder.bt_sign = convertView.findViewById(R.id.bt_sign);
			holder.ll_home = convertView.findViewById(R.id.ll_home);
			convertView.setTag(holder);
			viewMap.put(position, convertView);

		} else {
			convertView = viewMap.get(position);
			holder = (ViewHolder) convertView.getTag();
		}

		if (viewMap.size() > 20) {
			synchronized (convertView) {
				for (int i = 1; i < gd_da.getFirstVisiblePosition() - 3; i++) {
					viewMap.remove(i);
				}
				for (int i = gd_da.getLastVisiblePosition() + 3; i < getCount(); i++) {
					viewMap.remove(i);
				}
			}
		}

		setData(holder, position, convertView);

		return convertView;
	}

	private class ViewHolder {

		TextView jtys_list_name;// 姓名
		ImageView jtys_list_img,iv_tijian;// 头像
		TextView jtys_list_age;// 年龄
		TextView jtys_list_sex;
		TextView jtys_list_phone;// 手机号
		ImageView jtys_list_state_sign;// 签约状态
		ImageView jtys_list_state_unsign;// 签约状态
		LabelsView jtys_list_zdrq; // 重点人群
		TextView jtys_list_address;// 地址
        TextView jtys_jiandang_time;//建档时间
		Button btn_tijian;//体征监测
		ImageView iv_sex,iv_signing;
		TextView tv_phone,jtys_list_create,tv_cardid;
		Button bt_sign;
		LinearLayout ll_home;


	}

	/**
	 * 设置数据
	 * 
	 * @author 王婷婷
	 * @date 2017年4月8日 上午9:30:07
	 */
	@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
	private void setData(ViewHolder holder, final int position, View convertView) {

		final ARCHIVE_BASEINFO info = infoList.get(position);

		if(NovaApplication.isBoolean_zhuyuan()&&!TextUtils.isEmpty(info.getZHUYUANHAO())){
			convertView.setBackground(new WaterMarkBg(info.getZHUYUANHAO()));
		}
		if(info.getCREATED_DATE()!=null){
            holder.jtys_jiandang_time.setText("建档日期："+info.getCREATED_DATE());
        }else{
            holder.jtys_jiandang_time.setText("");
        }
		if(info.getCREATEMEN_NAME() != null){
			holder.jtys_list_create.setText("建档人："+info.getCREATEMEN_NAME());
		}else{
			holder.jtys_list_create.setText("");
		}

		if(info.getIDCARD() != null){
			holder.tv_cardid.setText("身份证："+info.getIDCARD());
		}

		holder.jtys_list_name.setText(info.getCUSTOMERNAME());
		int age = GlobalConts.getAge(info.getBIRTHDAY());
		if (age != -1) {
			holder.jtys_list_age.setText(String.valueOf(age));
		} else {
			holder.jtys_list_age.setText("");
		}
		holder.bt_sign.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(context, QYInfo.class);
				changeUserInfoToAllData(info);
				context.startActivity(intent);
			}
		});
		//
		holder.iv_signing.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, QYInfo.class);
				changeUserInfoToAllData(info);
				context.startActivity(intent);

			}
		});
		holder.iv_tijian.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				NovaApplication.setUserInfo(info);
				setSaveIDCard(info.getIDCARD());
				Intent intent = new Intent(context, BleMainActivity.class);
				context.startActivity(intent);
			}
		});

		List<BD_DD_INFO> bdxingbie = FDbManager.getInstance(context).findAllByWhereInInfoDB(BD_DD_INFO.class,
				"PARENTID = 'DM01-08'");
		String sex = "";
		for (BD_DD_INFO bdi : bdxingbie) {
			Log.e("8888",bdi.getID()+"**********"+info);
			if(TextUtils.isEmpty(info.getSEX())){
				info.setSEX("DM01-08_1");
			}
			if (info.getSEX().equals(bdi.getID())){
				sex = bdi.getDATAINFO();
			}
		}

		holder.jtys_list_sex.setText(sex);
		if(sex.equals("男")){
			holder.iv_sex.setImageDrawable(context.getDrawable(R.drawable.man));
			holder.jtys_list_zdrq.setLabelTextColor(R.color.appgreen);
		}else{
			holder.iv_sex.setImageDrawable(context.getDrawable(R.drawable.woman));
			holder.ll_home.setBackgroundResource(R.drawable.bottom_boxshadow2);
			holder.jtys_list_zdrq.setLabelTextColor(R.color.apppink);
		}
		holder.tv_phone.setText(info.getPHONE());
		holder.jtys_list_phone.setText(info.getPHONE());

        PopData popData = new PopData();

        popData.setPopInfo(holder.jtys_list_zdrq, info, PopData.TAG_WARNING, context, new PopData.OnClickListener() {
            @Override
            public void setOnClickItemListener(Object data) {
				NovaApplication.setUserInfo(info);
				setSaveIDCard(info.getIDCARD());
                String temp = ((LabelsBean) data).getName();
                Intent intent = null;
                if (PeopleType.CHILD_NAME.equals(temp)) {
                    //儿童
                    intent = new Intent(context, ChildActivity.class);
                } else if (PeopleType.WOMAN_NAME.equals(temp)) {
                    //孕妇
                    intent = new Intent(context, MaternityActivity.class);
                } else if (PeopleType.OLD_NAME.equals(temp)) {
                    //老年人
                    intent = new Intent(context, OlderActivity.class);

                } else if (PeopleType.GXY_NAME.equals(temp)) {
                    //高血压
                    intent = new Intent(context, GXYActivity.class);

                } else if (PeopleType.TNB_NAME.equals(temp)) {
                    //糖尿病
                    intent = new Intent(context, TNBActivity.class);

                } else if (PeopleType.GXB_NAME.equals(temp)) {
                    //冠心病
                    intent = new Intent(context, GXBActivity.class);

                } else if (PeopleType.NCZ_NAME.equals(temp)) {
                    //脑卒中
                    intent = new Intent(context, NCZActivity.class);
                } else if (PeopleType.JSB_NAME.equals(temp)) {
                    //精神疾病
                    intent = new Intent(context, JSJBctivity.class);
                } else if (PeopleType.FJH_NAME.equals(temp)) {
                    //肺结核
                    intent = new Intent(context, FJHActivity.class);
                }

                if (intent != null) {
                    context.startActivity(intent);
                }
            }
        });
		NovaApplication.setUserInfo(info);
		SPUtil.setstr_idCard(context, info.getIDCARD());
//		setDataDemo(holder);
		holder.jtys_list_address.setText("住址："+info.getHOUSEHOLD_ADDR());

		if (type.equals(JTYSDA.TYPE_ALL)) {
			Log.e("用户是否签约",info.getDISTRICT_ID()+"");
			if(TextUtils.isEmpty(info.getDISTRICT_ID())){
				holder.jtys_list_state_sign.setVisibility(View.GONE);
				holder.jtys_list_state_unsign.setVisibility(View.VISIBLE);
				holder.iv_signing.setVisibility(View.GONE);
				holder.bt_sign.setVisibility(View.VISIBLE);
			}else{
				holder.jtys_list_state_sign.setVisibility(View.VISIBLE);
				holder.jtys_list_state_unsign.setVisibility(View.GONE);
				holder.iv_signing.setVisibility(View.VISIBLE);
				holder.bt_sign.setVisibility(View.GONE);
			}
			
		} else if (type.equals(JTYSDA.TYPE_SIGN)) {
			holder.jtys_list_state_sign.setVisibility(View.VISIBLE);
			holder.jtys_list_state_unsign.setVisibility(View.GONE);
			holder.iv_signing.setVisibility(View.VISIBLE);
			holder.bt_sign.setVisibility(View.GONE);
		} else if (type.equals(JTYSDA.TYPE_UNSIGN)) {
			holder.jtys_list_state_sign.setVisibility(View.GONE);
			holder.jtys_list_state_unsign.setVisibility(View.VISIBLE);
			holder.iv_signing.setVisibility(View.GONE);
			holder.bt_sign.setVisibility(View.VISIBLE);
		}

		holder.ll_home.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {
					NovaApplication.setUserInfo(info);
					SPUtil.setstr_idCard(context, info.getIDCARD());
					if (info != null) {
						Log.e("档案点击事件！！！", info.getCUSTOMERNAME() + "\n" + info.getIDCARD());
						Intent intent = new Intent(context, MainActivity_Menu_Tj.class);
						context.startActivity(intent);
					}
				} else if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MEMBER.equals(strIntentId)) {
					Intent intent = new Intent();

					intent.putExtra("relation",info);

					((MemberDataActivity)context).setResult(RESULT_OK, intent);
					((MemberDataActivity)context).finish();

				}
			}
		});

		holder.ll_home.setOnLongClickListener(new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(View view) {
				if (GlobalContsJTYS.FRAGMENT_MEMBER_INTENT_ID_MAIN.equals(strIntentId)) {

					// IS_UPDATE //Y 未上传 N已上传
//					if ("Y".equals(infoList.get(position).getIS_UPDATE())) {
						showDeleteDialog(position);
//					}
				}
				return true;
			}
		});
	}

	private void showDeleteDialog(final int position) {
		new CommomDialog(context, R.style.dialog, "", new CommomDialog.OnCloseListener() {

			@Override
			public void onClick(Dialog dialog, boolean confirm) {
				if (confirm) {
					DeleteDAData.deleteDaData(infoList.get(position).getIDCARD());
					infoList.remove(position);
					notifyDataSetChanged();
					dialog.dismiss();
				}

			}

		}).setTitle("是否删除档案").setPositiveButton("删除").setNegativeButton("取消").show();
	}

	private void changeUserInfoToAllData(ARCHIVE_BASEINFO info) {
		List<ARCHIVE_BASEINFO> idCardList = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
				"IDCARD = '" + info.getIDCARD() + "'");
		ARCHIVE_BASEINFO userinfo11 = idCardList.get(0);
		userinfo11.setDISTRICT_ID(info.getDISTRICT_ID());
		userinfo11.setIS_UPDATE("Y");
		NovaApplication.fdbmanger.updata(userinfo11);
		info=userinfo11;
		NovaApplication.setUserInfo(info);
	}
	/**
	 * 保存idcard
	 *
	 * @param str_idCard
	 * @author 王婷婷
	 * @date 2017年6月9日 上午11:55:58
	 */
	private void setSaveIDCard(String str_idCard) {
		SPUtil.setstr_idCard(context, str_idCard);
	}



}
